package cn.edu.hznu;

import cn.edu.hznu.dao.IUserDao;
import cn.edu.hznu.domain.QueryVo;
import cn.edu.hznu.domain.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;



import java.io.InputStream;
import java.util.Date;
import java.util.List;

/**
 * Created by wjj on 2020/3/30
 */
public class CRUDtest {
    private  InputStream in=null;
    private  SqlSessionFactory sqlSessionFactory=null;
    SqlSession session=null;
    IUserDao userDao=null;
    @Before
    public void init()throws  Exception{
      in= Resources.getResourceAsStream("SqlMapConfig.xml");
      sqlSessionFactory=new SqlSessionFactoryBuilder().build(in);
      session=sqlSessionFactory.openSession();
      userDao=session.getMapper(IUserDao.class);
    }
    @After
    public  void destroy()throws  Exception{
        session.commit();
        session.close();
        in.close();
    }

    /*
    * 测试查询所有用户
    * */
    @Test
    public void  TestfindAll(){

        List<User>users=userDao.findAll();
        for(User user:users){
            System.out.println(user);
        }

    }
    /*
    * 增加新用户
    * */
    @Test
    public void  TestaddUser(){
        User user=new User();
        user.setAddress("杭州");
        user.setSex("男");
        user.setBirthday(new Date());
        user.setUsername("wjune");
        userDao.addUser(user);
        System.out.println(user);

    }

    /*
     * 更新用户
     * */
    @Test
    public void  TestupdateUser(){
        User user=new User();
        user.setId(50);
        user.setAddress("衢州");
        user.setSex("女");
        user.setBirthday(new Date());
        user.setUsername("何静雅");
        userDao.updateUser(user);
        System.out.println(user);
    }

    /*
     * 删除用户
     * */
    @Test
    public void  TestdeleteUser(){

        userDao.deleteUser(50);

    }

    /*
     * 查询单个用户根据id
     * */
    @Test
    public void  TestfindUserById(){

        User user=userDao.findUserById(49);
        System.out.println(user);
    }

    /*
     * 查询单个用户（模糊查询）
     * */
    @Test
    public void  TestfindUserByName(){

        List<User>users=userDao.findUserByName("%王%");
        for(User user:users){
            System.out.println(user);
        }
    }

    /*
     * 获取用户总数
     * */
    @Test
    public void  TestfindAllUser(){

        Integer num=userDao.findAllUser();
        System.out.println(num);
    }

    /*
     * 查询QueryVo单个用户（模糊查询）
     * */
    @Test
    public void  TestfindUserByVo(){
        QueryVo queryVo=new QueryVo();
        User user=new User();
        user.setUsername("%王%");
        queryVo.setUser(user);
        List<User>users=userDao.findUserByVo(queryVo);
        for(User use:users){
            System.out.println(use);
        }
    }



}
